package com.morder.provider;

import android.content.Context;
import android.os.AsyncTask;

public class LoginTask extends AsyncTask<Void, Void, String> implements BaseRequest.RequestListener {
  private LoginRequest mLoginRequest;
  private LoginTaskListener mListener;
  private Context mCtx;
  private String mNum;
  private String mPwd;

  public LoginTask(Context context) {
    super();
    mCtx = context;
  }

  public LoginTask execute(String phoneNum, String password, LoginTaskListener listener) {
    registerListener(listener);
    setLoginMessage(phoneNum, password);
    execute();
    return this;
  }

  private void setLoginMessage(String num, String pwd) {
    this.mNum = num;
    this.mPwd = pwd;
  }

  private void registerListener(LoginTaskListener listener) {
    unRegisterListener();
    mListener = listener;
  }

  private void unRegisterListener() {
    mListener = null;
  }

  @Override
  public void onRequestProcessInfo(String info) {
  }

  @Override
  protected String doInBackground(Void... params) {
    mLoginRequest = new LoginRequest(mCtx, mNum, mPwd);
    mLoginRequest.post("login.manu", "http://voip.sqt001.com/dosql.aspx", this);
    return null;
  }

  @Override
  public void onPreExecute() {
  }

  @Override
  public void onCancelled() {
  }

  @Override
  public void onPostExecute(String result) {
    if (!isCancelled()) {
      handleResult();
    }
  }

  private void handleResult() {
    int resultCode = mLoginRequest.getResuleCode();
    String msg = mLoginRequest.getMsg();
    if (BaseRequest.NORMAL_STATUS == resultCode) {
      handleNormalResult(msg);
    } else {
      handleExceptionResult(msg);
    }
  }

  private void handleNormalResult(String msg) {
    if (mListener != null) {
      mListener.onLoginFinish(true, msg);
    }
  }

  private void handleExceptionResult(final String msg) {
    if (mListener != null) {
      mListener.onLoginFinish(false, msg);
    }
  }

  public static interface LoginTaskListener {
    public void onLoginFinish(boolean success, final String reason);
  }
}
